package com.action;

import javax.servlet.ServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.manager.KeywordManager;
import com.manager.TaobaoManager;
import com.model.Keyword;
import com.model.ModuleConstant;
import com.model.Taobao;
import com.opensymphony.xwork2.ActionSupport;
import com.util.ServletUtils;
import com.util.TimeUtil;

@ParentPackage("json-default")
@Results({ @Result(name = "jsonResult", type = "json") })
@Namespace("/user")
public class TaobaoAction extends ActionSupport{
	
	@Autowired
	private TaobaoManager taobaoManager;
	@Autowired
	private KeywordManager keywordManager;
	
	private Taobao taobao = new Taobao();
	private Keyword	keyword;
	
	public Keyword getKeyword() {
		return keyword;
	}

	public void setKeyword(Keyword keyword) {
		this.keyword = keyword;
	}

	public TaobaoManager getTaobaoManager() {
		return taobaoManager;
	}

	public void setTaobaoManager(TaobaoManager taobaoManager) {
		this.taobaoManager = taobaoManager;
	}

	public Taobao getTaobao() {
		return taobao;
	}

	public void setTaobao(Taobao taobao) {
		this.taobao = taobao;
	}

	public String index(){
		String token = ServletUtils.getToken();
		ServletRequest request = ServletActionContext.getRequest();
		keyword = (Keyword)taobaoManager.findUnique("from Keyword t where t.token=? and t.model=?", new Object[]{token,ModuleConstant.TAOBAO});
		if(keyword == null){
			keyword = new Keyword();
			keyword.setKeyword("淘宝");
		}
		request.setAttribute("keyword", keyword);
		return "index";
	}
	
	public String update(){
		String token = ServletUtils.getToken();
		keyword.getTaobao().setAddTime(TimeUtil.getDate());
		keyword.getTaobao().setKeyword(keyword);
		keyword.getTaobao().setToken(ServletUtils.getToken());
		keyword.setModel(ModuleConstant.TAOBAO);
		ServletRequest request = ServletActionContext.getRequest();
		try {
			keywordManager.update(keyword);
		} catch (Exception e) {
			request.setAttribute("ret", "系统错误，请于管理员联系！");
			return "index";
		}
		request.setAttribute("ret", "更新成功");
		return "index";
	}
}
